var mysql  = require('mysql');
var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '',
      database : "the_net_v1",
      port     : 3306,
      multipleStatements: true
 	});


  module.exports.setBasicData = function(data){
	  		//data["update_by"] = user_in_session
	  		data["update_date"] = new Date();
	  		data["is_valid"] = 1; //valid
  		return data;
  }

  module.exports.insert = function(table, data){
  		var newData = data;//dont modify old data
  			newData = this.setBasicData(newData);
  			//newData['created_by'] = user_in_session;
  			newData['create_date'] = new Date();
  			
        var query = connection.query("INSERT INTO " + table + " set ? ", newData , function(err, rows)
        {
          if (err)
              console.log("Error inserting : %s ",err );
          console.log(query);
      	});

		return data;
  }


  module.exports.update = function(table, data, id){
  		var newData = data;//dont modify old data
  			newData = this.setBasicData(newData);

        var query = connection.query("UPDATE INTO " + table + " set ? WHERE id = ? ",[newData, id], function(err, rows)
        {
          if (err)
              console.log("Error updating : %s ",err );
          console.log(query);
      	});
		return data;
  }

    module.exports.search = function(table, data, id){

    	if(data.length > 0){
		        var query = connection.query("SELECT * from " + table + " WHERE ? ",[data], function(err, rows)
		        {
		          if (err)
		              console.log("Error searching : %s ",err );
		          console.log(query);
		      	});
	      }else{
		      	var query = connection.query("SELECT * from " + table , function(err, rows)
		        {
		          if (err)
		              console.log("Error searching : %s ",err );
		          console.log(query);
		      	});
	      }
		return data;
  }

  module.exports.delete = function(table, id){
  		var data = {is_valid : 1};
        var query = connection.query("UPDATE " + table + " set ? WHERE id = ? ",[data, id], function(err, rows)
        {
          if (err)
              console.log("Error deleting : %s ",err );
          console.log(query);
      	});
		return data;
  }

